﻿using Microsoft.Extensions.Configuration;
using BEurekaService;
using Microsoft.AspNetCore.Builder;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace BEurekaService//Microsoft.Extensions.DependencyInjection
{
    public static class EurekaServiceCollectionExtensions
    {
        public static IServiceCollection AddEurekaService(this IServiceCollection services, IConfiguration configuration)
        {
            //services.AddHttpClient();

            services.AddSingleton<IEurekaService, EurekaService>();

            return services;
        }

        //public static IApplicationBuilder UseEurekaService(this IApplicationBuilder app, IConfiguration configuration, IEurekaService _eurekaService)
        //{
        //    //services.AddHttpClient();

        //    //_eurekaService.RegisterService("myServiceName", new Uri("http://127.0.0.1:8081/Eureka"), HealthCheck );
        //    _eurekaService.RegisterService("myServiceName", new Uri("http://127.0.0.1:8081/Eureka"), () => { return true; });
        //    return app;
        //}

        //不想再传参数进来了，好扩展consul 服务发现
        public static IApplicationBuilder UseEurekaService(this IApplicationBuilder app, IOptions<EurekaServicexml> consulService)
        {
            //services.AddHttpClient();
            IEurekaService _eurekaService = app.ApplicationServices.GetService<IEurekaService>();


            Urls._eurekaRootUrl = $"http://{consulService.Value.IP}:{consulService.Value.Port}";
            Urls._eurekaQueryInstancesByAppIdUrl = Urls._eurekaRootUrl + "/eureka/apps/{0}";// = $"http://{consulService.Value.IP}:{consulService.Value.Port}";
            Urls._eurekaRegisterInstanceUrl = Urls._eurekaRootUrl + "/eureka/apps/{0}";
            Urls._eurekaSendHeartBeatUrl = Urls._eurekaRootUrl + "/eureka/apps/{0}/{1}";

            //_eurekaService.RegisterService("myServiceName", new Uri("http://127.0.0.1:8081/Eureka"), HealthCheck );
            //_eurekaService.RegisterService("myServiceName", new Uri("http://127.0.0.1:8081/Eureka"), () => { return true; });

            //$"http://{consulService.Value.IP}:{consulService.Value.Port}/Eureka"
            string[] strs = consulService.Value.ServiceUrl.Split(':');
            _eurekaService.RegisterService($"{consulService.Value.Name}", new Uri($"http://{strs[1].Replace("/","")}:{strs[2].Replace("/","")}/"), () => { return true; }).Wait();

 

 


            Uri[] urls = _eurekaService.GetEntryPoints(consulService.Value.Name).Result;


            return app;
        }

        private static bool HealthCheck()
        {
            return true;
        }
    }
}
